package com.orhon.expert.user.controller;


import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.orhon.expert.user.common.UserException;
import com.orhon.expert.user.common.UserException.Type;
import com.orhon.expert.user.model.SysUserEntity;
import com.orhon.expert.user.utils.JwtHelper;
import com.orhon.expert.user.utils.SysContent;


/**
 * Controller公共组件

 */
public abstract class AbstractController {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private StringRedisTemplate redisTemplate;
	protected SysUserEntity getUsers() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		String token=request.getHeader("token");
		Map<String, String> map = null;
	    try {
	      map = JwtHelper.verifyToken(token);
	    } catch (Exception e) {
	      throw new UserException(Type.USER_NOT_LOGIN,"User not login");
	    }
	    String username =  map.get("username");
	    String userid =  map.get("userid");
	    System.out.println(userid);
	    renewToken(token, username);
	    SysUserEntity user = new SysUserEntity();
	    user.setUsername(username);
	    if(Strings.isNotBlank(map.get("userid"))){
	    	user.setUserId(Long.parseLong(map.get("userid")));
	    }
	    return user;
	}
	protected  Long getUserId() {
		return getUsers().getUserId();
	}
	private String renewToken(String token, String username) {
	    redisTemplate.opsForValue().set(username, token);
	    redisTemplate.expire(username, 30, TimeUnit.MINUTES);
	    return token; 
	  }
}
